using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Threading;
using Tracker.Mobile.Droid.TrackerWebService;

namespace Tracker.Mobile.Droid.Activities
{
    [Activity(Label = "Login")]
    public class Login : BaseActivity
    {
        private EditText _username;
        private EditText _password;
        private Button _login;
        private Button _newUser;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Login);
            Initialize();
        }

        private void Initialize()
        {
            _username = FindViewById<EditText>(Resource.Id.LoginUsername);
            _password = FindViewById<EditText>(Resource.Id.LoginPassword);
            _login = FindViewById<Button>(Resource.Id.Login);
            _newUser = FindViewById<Button>(Resource.Id.NewUser);
            _login.Click += (sender, args) =>
            {
                ProgressDialog dialog = Util.CreateProgressDialog(this, ProgressDialogStyle.Spinner, "Please Wait", "Logging in");

                ThreadPool.QueueUserWorkItem(state =>
                {
                    var dto = new UserDTO();
                    dto.Username = _username.Text;
                    dto.Password = _password.Text;

                    dto = WebService.Login(dto);

                    if (dto != null)
                    {
                        UserID = dto.ID;
                        Username = dto.Username;
                        Email = dto.Email;

                        Intent home = new Intent(this, typeof(Home));
                        StartActivity(home);
                    }
                    else
                    {
                        RunOnUiThread(() =>
                        {
                            dialog.Dismiss();
                            Toast.MakeText(this, "Invalid username or password", ToastLength.Long).Show();
                        });
                    }
                });
            };
            _newUser.Click += (sender, args) =>
            {
                Intent register = new Intent(this, typeof(Register));
                StartActivity(register);
            };
        }
    }
}